package io.renren.modules.quickService.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.quickService.dao.AreacodeDao;
import io.renren.modules.quickService.entity.AreacodeEntity;
import io.renren.modules.quickService.service.AreacodeService;
import io.renren.modules.quickService.vo.AreaCodeVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("areacodeService")
public class AreacodeServiceImpl extends ServiceImpl<AreacodeDao, AreacodeEntity> implements AreacodeService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<AreacodeEntity> page = this.selectPage(
                new Query<AreacodeEntity>(params).getPage(),
                new EntityWrapper<AreacodeEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AreaCodeVO> getCityListByLevel(Integer cLevel) {
        return baseMapper.getCityListByLevel(cLevel);
    }

    @Override
    public List<AreaCodeVO> getChildrenList(Long parentId) {
        return baseMapper.queryChildrenList(parentId);
    }

    @Override
    public List<AreaCodeVO> getCascadeAreas() {
        //default cascade level 3
        List<AreaCodeVO> provinces = this.getCityListByLevel(1);
        for (AreaCodeVO province : provinces) {
            List<AreaCodeVO> cities = this.getChildrenList(province.getAreacodeId());
            province.setChildren(cities);
            for (AreaCodeVO city : cities) {
                List<AreaCodeVO> areas = this.getChildrenList(city.getAreacodeId());
                city.setChildren(areas);
            }
        }
        return provinces;
    }

    @Override
    public String[] getCascadeAreaByLastAdminCode(String adminCode) {
        String[] adminCodes = new String[3];
        adminCodes[2] = adminCode;
        AreaCodeVO queryVO = getParentArea(adminCode);
        adminCodes[1] = queryVO.getAdminCode();
        queryVO = getParentArea(queryVO.getAdminCode());
        adminCodes[0] = queryVO.getAdminCode();
        return adminCodes;
    }

    @Override
    public String getAddressByLastAdminCode(String adminCode) {
        AreacodeEntity areacodeEntity = new AreacodeEntity();
        areacodeEntity.setAdminCode(adminCode);
        areacodeEntity = baseMapper.selectOne(areacodeEntity);
        if (areacodeEntity == null) return null;// 防止空指针
        return areacodeEntity.getProvince() + "-" + areacodeEntity.getPrefectureName() + "-" + areacodeEntity.getCName();
    }

    private AreaCodeVO getParentArea(String adminCode) {
        return baseMapper.queryParentArea(adminCode);
    }
}
